package org.mx.spring.i18n;

import org.mx.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.AbstractMessageSource;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.env.Environment;

/**
 * 描述： 根据配置创建Properties消息资源包的创建器
 *
 * @author john peng
 * Date time 2019/8/15 9:32 AM
 */
public class PropertiesI18nMessageResourceCreator implements I18nMessageResourceCreator {
    private static final Logger logger = LoggerFactory.getLogger(PropertiesI18nMessageResourceCreator.class);
    private Environment env;
    private long reloadTimeout;

    /**
     * 默认的构造函数
     *
     * @param env           Spring IoC容器上下文环境
     * @param reloadTimeout 重新加载的超时值
     */
    public PropertiesI18nMessageResourceCreator(Environment env, long reloadTimeout) {
        super();
        this.env = env;
        this.reloadTimeout = reloadTimeout;
    }

    /**
     * {@inheritDoc}
     *
     * @see I18nMessageResourceCreator#create()
     */
    @Override
    public AbstractMessageSource create() {
        String basenames = env.getProperty("i18n.properties.basenames");
        if (StringUtils.isBlank(basenames)) {
            if (logger.isErrorEnabled()) {
                logger.error("The basename for the properties message resource is blank.");
                return null;
            }
        }
        String encoding = env.getProperty("i18n.properties.encoding", "UTF-8");
        ReloadableResourceBundleMessageSource reloadableResourceBundleMessageSource = new ReloadableResourceBundleMessageSource();
        // 设置翻译资源路径
        reloadableResourceBundleMessageSource.setBasenames(StringUtils.split(basenames));
        // 设置重载时间间隔，单位毫秒
        reloadableResourceBundleMessageSource.setCacheMillis(reloadTimeout);
        // 设置字符集
        reloadableResourceBundleMessageSource.setDefaultEncoding(encoding);
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Create a properties message resource[%s].", basenames));
        }
        return reloadableResourceBundleMessageSource;
    }
}
